Second minimum node in a binary tree¶
Time: O(N); Space: O(H); easy
Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node’s value is the smaller value among its two sub-nodes. More formally, the property
root.val = min(root.left.val, root.right.val)
always holds.
Given such a binary tree, you need to output the second minimum value in the set made of all the nodes’ value in the whole tree.
If no such second minimum value exists, output -1 instead.
Example 1:
Input: root = {TreeNode} [2,2,5,None,None,5,7]
2
/ \
2 5
/ \
5 7
Output: 5
Explanation:
The smallest value is 2, the second smallest value is 5.
Example 2:
Input: root = {TreeNode} [2,2,2]
2
/ \
2 2
Output: -1
Explanation:
The smallest value is 2, but there isn’t any second smallest value.
[1]:
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
[2]:
import heapq
class Solution1(object):
"""
Time: O(N)
Space: O(H)
"""
def findSecondMinimumValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def findSecondMinimumValueHelper(root, max_heap, lookup):
if not root:
return
if root.val not in lookup:
heapq.heappush(max_heap, -root.val)
lookup.add(root.val)
if len(max_heap) > 2:
lookup.remove(-heapq.heappop(max_heap))
findSecondMinimumValueHelper(root.left, max_heap, lookup)
findSecondMinimumValueHelper(root.right, max_heap, lookup)
max_heap, lookup = [], set()
findSecondMinimumValueHelper(root, max_heap, lookup)
if len(max_heap) < 2:
return -1
return -max_heap[0]
[4]:
s = Solution1()
root = TreeNode(2)
root.left = TreeNode(2)
root.right = TreeNode(5)
root.right.left = TreeNode(5)
root.right.right = TreeNode(7)
assert s.findSecondMinimumValue(root) == 5
root = TreeNode(2)
root.left = TreeNode(2)
root.right = TreeNode(2)
assert s.findSecondMinimumValue(root) == -1
See also:¶
https://leetcode.com/problems/second-minimum-node-in-a-binary-tree
https://www.lintcode.com/problem/second-minimum-node-in-a-binary-tree/description
Related problems:¶
https://www.lintcode.com/problem/kth-smallest-element-in-a-bst